package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.constants.admin.AdminConstants.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //参数校验
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数错误");
        }
        //检查用户是否存在
        LambdaQueryWrapper<AdUser> wrapper = new LambdaQueryWrapper<>();
        AdUser adUser = this.getOne(wrapper.eq(AdUser::getName, dto.getName()));
        if (adUser==null){
            //不存在
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //检查密码是否正确
        String password = adUser.getPassword();
        String s = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());
        if (!s.equals(password)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }
        //检查用户状态是否有效
        if (!adUser.getStatus().equals(AdminConstants.USER_STATUS_ISSTATUS)){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //修改最近登录时间
        adUser.setCreatedTime(new Date());
        this.updateById(adUser);
        //颁发token
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        //返回数据
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(adUser,adUserVO);
        Map map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUserVO);
        return ResponseResult.okResult(map);
    }
}
